package cn.ibizlab.util.tenant;

import cn.ibizlab.util.security.AuthenticationUser;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

@Component
@EnableConfigurationProperties(TenantProperties.class)
@ConditionalOnExpression("'${ibiz.tenant.enabled:false}'.equals('true')")
public class TenantHandler implements TenantLineHandler {

    @Autowired
    private TenantProperties tenantProperties;

    @Override
    public Expression getTenantId() {
        String tenantId = AuthenticationUser.getAuthenticationUser().getDc();
        if( ObjectUtils.isEmpty(tenantId) )
            return null;
        else
            return new StringValue(tenantId);
    }

    @Override
    public String getTenantIdColumn() {
        return tenantProperties.getTenantIdColumn();
    }

    @Override
    public boolean ignoreTable(String tableName) {
        return  tenantProperties.getIgnoreTables().stream().anyMatch(table -> table.equalsIgnoreCase(tableName));
    }


}
